/**
 * 
 * 深圳市店联电子商务
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.systemView;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableRowSorter;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;

import com.ruipengkj.bean.MonthMarkeView;
import com.ruipengkj.bean.TSaleactSummary;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.DataPackageComponent;
import com.ruipengkj.component.JLabelJRadioGroupButtonComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.jpanel.QueryPanel;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.MonthMarkeModel;
import com.ruipengkj.service.MonthMarkeViewService;
import com.ruipengkj.view.base.BasePagePanel;

/**
 * 说明： 营销评估
 * 
 * @Author：朱攀
 * @Date：2012-07-12
 */
public class MarkePanel extends BasePagePanel<TSaleactSummary> implements
		Runnable {

	private static final long serialVersionUID = 1L;
	// --------------------定义弹出框-----------------------------------


	private DataPackageComponent sTime = null;// 发卡时间
	private DataPackageComponent eTime = null;// 时间
	private JButton selectButton = null;// 查询按钮
	private JButton dayButton = null;// 查询天报表
	private JButton weekButton = null; // 查询周报表
	private JLabelJRadioGroupButtonComponent selectRadio=null;  //月

	

	private JPanel jp1; // 饼形图
	private JSplitPane jfreeJsp;

	private JTable table;
	// private MemberQueryCardModel memberQueryCardModel;
	private MonthMarkeModel monthMarkeModel;

	private JScrollPane tableJsp;
	private MonthMarkeViewService monthMarkeViewService;

	public MarkePanel() {
		monthMarkeViewService = BuildSpringApplication.getInstance()
				.getMonthMarkeViewServiceImpl();
		this.setLayout(new BorderLayout());
		this.init();
		this.initListener();

	}

	private void init() {
		monthMarkeModel = new MonthMarkeModel();
		table=uiFactory.createRPJTable(monthMarkeModel, null, this, 30, JLabel.CENTER);
		tableJsp=uiFactory.createJScrollPane(table);
		
		//table设置列宽度 AUTO_RESIZE_SUBSEQUENT_COLUMNS 填满父容器  JTable.AUTO_RESIZE_OFF 自适应
		table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
		
		

		this.add(this.topPanel(), BorderLayout.NORTH);
		// this.add(tableJsp, BorderLayout.CENTER);

		// jfreeJsp=uiFactory.createJPanelWithComponents(tableJsp,
		// FreeBarChart(), 100);
		// 产生一个分隔面板 分隔面板1 分隔面板2 水平或垂直分割 分割条位置 分割条宽度 是否可收起
		jfreeJsp = uiFactory.createJSplitPane(tableJsp, FreeBarChart(), 0, 120,
				2, true);
		this.add(jfreeJsp, BorderLayout.CENTER);
		// 排序
		TableRowSorter<MonthMarkeModel> tableRowSorter = new TableRowSorter<MonthMarkeModel>(
				monthMarkeModel);
		table.setRowSorter(tableRowSorter);
	}

	private JPanel topPanel() {
		QueryPanel queryPanel=new QueryPanel("营销评估",ImageFactory.loadImage(ImageFactory.FUN_3_ICON_3));
		JPanel jp = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		 
		selectButton = new RPJButtonBlue("查询");
		sTime = new DataPackageComponent("开始时间：", 15);
		eTime = new DataPackageComponent("结束时间：", 15);
		String[] options = {"月","周","日"};
		selectRadio= new JLabelJRadioGroupButtonComponent("", options, 1);

		Date d = new Date();
		Date d1 = new Date();
		Date stime = sTime.getDate();
		Date etime = eTime.getDate();
		if (etime == null) {
			eTime.setDate(d);
		}
		if (stime == null) {
			d1.setDate(1);//
			sTime.setDate(d1);
		}

		jp.add(sTime);
		jp.add(eTime);
		jp.add(selectRadio);
		jp.add(selectButton);
		queryPanel.add(jp);
		return queryPanel;
	}

	private void initListener() {
		selectButton.addActionListener(this);
		

	}

	@Override
	public void run() {
		this.termQuery();
		//termQuery1();
	}

	// 查询月的汇总
	protected void termQuery() {

		final MonthMarkeView monthMarkeView = new MonthMarkeView();
		final String selectText=selectRadio.getSelectOptionText();

		new Thread() {
			public void run() {
				tableJsp.getViewport().remove(table);
				tableJsp.getViewport().add(waitComponent);
				List<MonthMarkeView> markeList=null;
				try {

						SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
						if(selectText.trim().equals("月")){
							 markeList = monthMarkeViewService.findDayMonthService(monthMarkeView, df.format(sTime.getDate()), df.format(eTime.getDate()));
							
						}else if(selectText.trim().equals("周")){
							markeList = monthMarkeViewService.findWeekService(monthMarkeView, df.format(sTime.getDate()), df.format(eTime.getDate()));
						}else if(selectText.trim().equals("日")){
							 markeList = monthMarkeViewService.findDayService(monthMarkeView, df.format(sTime.getDate()), df.format(eTime.getDate()));
							
						}
						if (markeList != null) {
							Util.clearTableRowSorter(table);
							monthMarkeModel.setRowData(markeList);
						
						// ------------------------- 柱状图 -------------------------------------
						jp1.removeAll();
						DefaultCategoryDataset DataSet;
						JFreeChart chart;
						// 构造DataSet
						DataSet = new DefaultCategoryDataset();
						//List<MonthMarkeView> rs = monthMarkeViewService.findDayMonthService(monthMarkeView, df.format(sTime.getDate()), df.format(eTime.getDate()));
						MonthMarkeView mssv;
						for (int i = 0, l = markeList.size(); i < l; i++) {
							mssv = markeList.get(i);

							DataSet.addValue(mssv.getSaleCount(), "count", mssv.getMonData());
							DataSet.addValue(mssv.getSaleTotalMoney(), "money",mssv.getMonData());
							DataSet.addValue(mssv.getBookCount(), "book", mssv.getMonData());
							DataSet.addValue(mssv.getVCount(), "visit",mssv.getMonData());
						}

						// 创建柱形图
						chart = ChartFactory.createBarChart3D("销售报表",
								"销售统计", "", DataSet, PlotOrientation.VERTICAL,
								false, false, false);
						
						//解决中文乱码问题(关键)
						   CategoryPlot plot = chart.getCategoryPlot();// 获得图表区域对象
						   CategoryAxis categoryAxis = plot.getDomainAxis(); 
						   CategoryAxis domainAxis = plot.getDomainAxis();
						   NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();
						   TextTitle textTitle = chart.getTitle();
						   textTitle.setFont(new Font("黑体", Font.PLAIN, 20));
						   domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));
						   domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));
						   numberaxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));
						   numberaxis.setLabelFont(new Font("黑体", Font.PLAIN, 12));
						   
						// 横轴上的 Lable 45度倾斜
						     categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
						   
						   // 设置图表的颜色
						   org.jfree.chart.renderer.category.BarRenderer3D renderer;
						   renderer = new org.jfree.chart.renderer.category.BarRenderer3D();
						   renderer.setBaseOutlinePaint(Color.red);
						   renderer.setSeriesPaint(0, new Color(0, 255, 255));// 计划柱子的颜色为青色
						   renderer.setSeriesOutlinePaint(0, Color.BLACK);// 边框为黑色
						   renderer.setSeriesPaint(1, new Color(0, 255, 0));// 实报柱子的颜色为绿色
						   renderer.setSeriesOutlinePaint(1, Color.red);// 边框为红色
						   renderer.setItemMargin(0.1);// 组内柱子间隔为组宽的10%

						   // 显示每个柱的数值，并修改该数值的字体属性
						   renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
						   renderer.setItemLabelFont(new Font("黑体", Font.BOLD, 12));// 12号黑体加粗
						   renderer.setItemLabelPaint(Color.black);// 字体为黑色
						   renderer.setItemLabelsVisible(true);

						   plot.setRenderer(renderer);// 使用我们设计的效果
						   
						   
						// 用来放置图表
						ChartPanel panel = new ChartPanel(chart);
						//设置显示大小
						panel.setPreferredSize(new  java.awt.Dimension(1000,450));
						//panel.setBounds(100, 100, 1000, 1000);
						jp1.add(panel, BorderLayout.CENTER);
						
						//jp1.add(panel, BorderLayout.CENTER);
							// ------------------------- 柱状图-------------------------------------

						SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
						
								tableJsp.getViewport().remove(waitComponent);
								tableJsp.getViewport().add(table);
								Util.setJTabelAutoClumnWidth(table);
							}
						});
					} else {
						// 没有订单数据
						tableJsp.getViewport().remove(waitComponent);
						tableJsp.getViewport().add(table);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}.start();
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == selectButton) {
			// 查询月的统计报表
			termQuery();
		}

		else if (e.getSource() == dayButton) { // ---------------------------------------------------
			// 查询天的统计报表
			//termQuery1();

		} else if (e.getSource() == weekButton) { // ---------------------------------------------------
			//查询周的统计报表
			//termQueryWeek();

		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_ENTER) {
			// if(e.getSource()==nameTF.getText()||e.getSource() ==
			// tel.getText()){
			if (e.getSource() == dayButton) {
				// 增加自定义优惠卷
				// addSalect();
			} else if (e.getSource() == table) { // --------------------------------------------------
				if (e.getKeyCode() == KeyEvent.VK_DELETE) {
					// 删除优惠卷
					// deleteSaleact();
				}
			} 
		}

	}

	// ------------------------------- 柱状图 ----------------------------------
	public JPanel FreeBarChart() {
		//jp1 = new JPanel();
		jp1 = uiFactory.createFlowJPanel();
		
		//jp1.setBounds(1000, 1000, 1000, 400);
		return jp1;
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub
		
	}

}
